<template>
  <div id="app">
    <div>
      <el-button @click="checkupdate">检测更新</el-button>
    </div>
    <div v-if="state.dialogVisible">有更新版本{{ version }}</div>

    <el-dialog
      title="正在更新新版本,请稍候..."
      v-model.sync="state.dialogVisible"
      width="60%"
      :close-on-click-modal="state.closeOnClickModal"
      :close-on-press-escape="state.closeOnPressEscape"
      :show-close="state.showClose"
      center
    >
      <div style="width: 100%; height: 20vh; line-height: 20vh; text-align: center">
        <el-progress
          status="success"
          :text-inside="true"
          :stroke-width="20"
          :percentage="state.percentage"
          :width="state.strokeWidth"
          :show-text="true"
        ></el-progress>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startUpdate"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, toRefs, onMounted, ref } from 'vue'
const state = reactive({
  dialogVisible: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  showClose: false,
  percentage: 0,
  strokeWidth: 200
})

const version = ref('')

const checkupdate = () => {
  console.log('检测更新1')
  window.electron.ipcRenderer.invoke('check-update')
}

const startUpdate = () => {
  console.log('开始更新1')
  window.electron.ipcRenderer.invoke('start-update')
}

onMounted(() => {
  //接收主进程版本更新消息
  window.electron.ipcRenderer.on('message', (event, arg) => {
    // for (var i = 0; i < arg.length; i++) {
    console.log('前端监听到了@@@@@@@@@@@@@@@', arg)
    if ('update-available' == arg.cmd) {
      //显示升级对话框
      version.value = arg.data.version
      console.log('🚀 ~ 显示升级对话框:', version)

      state.dialogVisible = true
    } else if ('download-progress' == arg.cmd) {
      //更新升级进度
      console.log('🚀 ~ 更新升级进度:')
      /**
  	     *
  	     * message{bytesPerSecond: 47673
  	      delta: 48960
  	      percent: 0.11438799862426002
  	      total: 42801693
  	      transferred: 48960
  	      }
  	     */
      console.log(arg.data.percent)
      let percent = Math.round(parseFloat(arg.data.percent))
      state.percentage = percent
    } else if ('error' == arg.cmd) {
      state.dialogVisible = false
      console.log('🚀 ~ 更新失败:')
    }
    // }
  })
})
</script>
